package com.dmxh.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dmxh.result.Result;
import com.dmxh.result.ResultConstant;
import com.dmxh.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
public class LoginFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //判断是否为登陆请求,若是则直接跳过
        String path = request.getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String[] goPath = {"/cart/**"};
        for (String s : goPath) {
            if (!antPathMatcher.match(s, path)) {
                return chain.filter(exchange);
            }
        }
        //获取传入参数
        HttpHeaders headers = request.getHeaders();
        //获取第一个请求参数并进行判断
        String token = headers.getFirst("adminToken");
        if (token == null || "".equals(token)) {
            return getVoidMono(exchange);
        }
        try {
            JwtUtil.parseJwt(token);
            return chain.filter(exchange);
        } catch (Exception e) {
            return getVoidMono(exchange);
        }
    }
    private Mono<Void> getVoidMono(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        //设置响应码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //设置响应头编码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //设置响应内容
        Result<Object> result = new Result<>(ResultConstant.ERROR_TOKEN.getCode(), ResultConstant.ERROR_TOKEN.getMessage());
        //不输出为null的字段
        byte[] bytes = JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }
}
